package com.learn.thread.demo02;

import java.io.FileWriter;
import java.io.PrintWriter;

/**
 * 获取和设置线程信息
 * @author Java丶小明
 * @date 2021/6/25 15:11
 */
public class ThreadDemo {
    private static final int TEN = 10;

    public static void main(String[] args) {
        //创建一个大小为10的Thread类的数组和一个大小为10的Thread.State数组来保存将要执行的线程和它们的状态。
        Thread[] threads = new Thread[TEN];
        Thread.State[] status = new Thread.State[TEN];
        //创建10个Calculator类的对象，每个初始为不同的数字，然后分别用10个线程来运行它们。把其中5个的优先值设为最高，把另外5个的优先值为最低。
        for (int i = 0; i < TEN; i++) {
            threads[i] = new Thread(new Calculator(i));
            if (i % 2 == 0) {
                threads[i].setPriority(Thread.MAX_PRIORITY);
            } else {
                threads[i].setPriority(Thread.MIN_PRIORITY);
            }
            threads[i].setName("Thread " + i);
        }
        //创建一个 PrintWriter对象用于把线程状态的改变写入文档。
        try (FileWriter file = new FileWriter("C:\\test\\Thead-Run.log");
             PrintWriter printWriter = new PrintWriter(file)) {
            //把10个线程的状态写入文档。现在，它成为NEW.
            for (int i = 0; i < TEN; i++) {
                printWriter.println("Main : Status of Thread " + i + " : " + threads[i].getState());
                status[i] = threads[i].getState();
            }
            //开始执行这10个线程
            for (int i = 0; i < TEN; i++) {
                threads[i].start();
            }
            //直到这10个线程执行结束，我们会一直检查它们的状态。如果发现它的状态改变，就把状态记入文本。
            boolean finish = false;
            while (!finish) {
                for (int i = 0; i < TEN; i++) {
                    if (threads[i].getState() != status[i]) {
                        writeThreadInfo(printWriter, threads[i], status[i]);
                        status[i] = threads[i].getState();
                    }
                }
                finish = true;
                for (int i = 0; i < TEN; i++) {
                    finish = finish && (threads[i].getState() == Thread.State.TERMINATED);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 写入线程信息
     * @param pw 输出类
     * @param thread 线程
     * @param state 状态
     */
    private static void writeThreadInfo(PrintWriter pw, Thread thread, Thread.State state) {
        pw.printf("Main : Id %d - %s\n", thread.getId(), thread.getName());
        pw.printf("Main : Priority: %d\n", thread.getPriority());
        pw.printf("Main : Old State: %s\n", state);
        pw.printf("Main : New State: %s\n", thread.getState());
        pw.printf("Main : ************************************\n");
    }
}
